package com.lujianfei.netease_android_float_window

import android.content.Context
import android.graphics.PixelFormat
import android.os.Build
import android.view.*
import android.view.View.OnTouchListener
import android.widget.ImageView
import android.widget.TextView
import java.lang.reflect.Field

class FloatWindowManager(context: Context) {
    private var wm: WindowManager? = null
    private var wmParams: WindowManager.LayoutParams? = null
    private var view: View? = null
    private var txt_floating: TextView? = null
    private var close: ImageView? = null
    private var mTouchStartX = 0f
    private var mTouchStartY = 0f
    private var x = 0f
    private var y = 0f
    private val statusHeight: Int
    private var hasAdd = false
    init {
        initView(context)
        initEvent()
        statusHeight = statusBarHeight
    }
    private fun initEvent() {
        view?.setOnTouchListener { v, event -> // 获取相对屏幕的坐标，即以屏幕左上角为原点
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    // 获取相对View的坐标，即以此View左上角为原点
                    mTouchStartX = event.x
                    mTouchStartY = event.y
                }
                MotionEvent.ACTION_MOVE -> {
                    x = event.rawX
                    y = event.rawY - statusHeight // 系统状态栏的高度
                    updateViewPosition()
                }
                MotionEvent.ACTION_UP -> {
                    x = event.rawX
                    y = event.rawY - statusHeight // 系统状态栏的高度
                    updateViewPosition()
                    mTouchStartY = 0f
                    mTouchStartX = mTouchStartY
                }
            }
            true
        }
    }

    private fun initView(context: Context) {
        wm = context.applicationContext.getSystemService(
                Context.WINDOW_SERVICE) as WindowManager
        view = LayoutInflater.from(context).inflate(R.layout.floatwindow, null)
        txt_floating = view?.findViewById(R.id.txt_floating)
        close = view?.findViewById(R.id.close)
        close?.setOnClickListener {
            removeView()
        }
        // 设置LayoutParams(全局变量）相关参数
        wmParams = WindowManager.LayoutParams()
        if (Build.VERSION.SDK_INT >= 26) {
            wmParams?.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
        } else {
            wmParams?.type = WindowManager.LayoutParams.TYPE_PHONE
        }
        wmParams?.apply {
            flags = flags or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
            gravity = Gravity.LEFT or Gravity.TOP // 调整悬浮窗口至左上角
            // 以屏幕左上角为原点，设置x、y初始值
            x = 0
            y = 0
            // 设置悬浮窗口长宽数据
            width = WindowManager.LayoutParams.WRAP_CONTENT
            height = WindowManager.LayoutParams.WRAP_CONTENT
            format = PixelFormat.RGBA_8888
        }
    }

    fun start() {
        if (!hasAdd) {
            wm?.addView(view, wmParams)
            hasAdd = true
        }
    }

    fun setText(text: String?) {
        if (hasAdd && txt_floating != null) txt_floating?.text = text
    }

    private fun updateViewPosition() { // 更新浮动窗口位置参数
        wmParams?.x = (x - mTouchStartX).toInt()
        wmParams?.y = (y - mTouchStartY).toInt()
        wm?.updateViewLayout(view, wmParams)
    }

    fun removeView() {
        if (hasAdd) {
            wm?.removeView(view)
        }
        hasAdd = false
    }

    private val statusBarHeight: Int
        private get() {
            val c: Class<*>
            val obj: Any
            val field: Field
            val x: Int
            var sbar = 0
            try {
                c = Class.forName("com.android.internal.R\$dimen")
                obj = c.newInstance()
                field = c.getField("status_bar_height")
                x = field[obj].toString().toInt()
                sbar = MyApplication.INSTANCE.resources.getDimensionPixelSize(x)
            } catch (e1: Exception) {
                e1.printStackTrace()
            }
            return sbar
        }
}